import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

import './Xq.css';
import SearchChat from './components/chat/SearchChat';

interface UserData {
  username: string;
  image: string;
  isLoggedIn: boolean;
}

interface XqProps {
  currentUser: UserData;
  selectedUser: {
    username: string;
    image: string;
  } | null;
}

const Xq: React.FC<XqProps> = ({ currentUser: _currentUser, selectedUser }) => {
  const navigate = useNavigate();
  const [doNotDisturb, setDoNotDisturb] = useState(false);
  const [pinChat, setPinChat] = useState(false);
  const [reminders, setReminders] = useState(false);
  const [showBackgroundModal, setShowBackgroundModal] = useState(false);
  const [selectedBackground, setSelectedBackground] = useState<string>('');
  const [showClearChatModal, setShowClearChatModal] = useState(false);
  const [isClearingChat, setIsClearingChat] = useState(false);
  const [showSearchChat, setShowSearchChat] = useState(false);

  // 预设背景图片
  const presetBackgrounds = [
    '/img/1.png',
    '/img/2.png',
    '/img/3.png',
    '/img/4.png',
    '/img/5.png',
    '/img/6.png',
    '/img/7.png',
  ];

  // 获取当前聊天的背景图片和置顶状态
  useEffect(() => {
    if (selectedUser) {
      // 获取背景图片
      const chatBackground = localStorage.getItem(
        `chatBackground_${selectedUser.username}`
      );
      if (chatBackground) {
        setSelectedBackground(chatBackground);
      }

      // 获取置顶状态
      const pinChatStatus = localStorage.getItem(
        `pinChat_${selectedUser.username}`
      );
      if (pinChatStatus) {
        setPinChat(pinChatStatus === 'true');
      }
    }
  }, [selectedUser]);

  // 获取置顶状态
  useEffect(() => {
    if (selectedUser) {
      const isPinned =
        localStorage.getItem(`pinChat_${selectedUser.username}`) === 'true';
      setPinChat(isPinned);
    }
  }, [selectedUser]);

  // 处理置顶聊天切换
  const handlePinChatToggle = () => {
    if (!selectedUser) return;

    const newPinStatus = !pinChat;
    setPinChat(newPinStatus);

    // 保存到localStorage
    localStorage.setItem(
      `pinChat_${selectedUser.username}`,
      newPinStatus.toString()
    );

    // 触发全局更新事件
    localStorage.setItem('pinChat_updated', Date.now().toString());
    window.dispatchEvent(new CustomEvent('pinChatUpdated'));
  };

  // 处理搜索聊天内容点击
  const handleSearchChatClick = () => {
    setShowSearchChat(true);
  };

  // 处理搜索页面返回
  const handleSearchBack = () => {
    setShowSearchChat(false);
  };

  // 处理搜索结果消息点击
  const handleSearchMessageClick = (message: any) => {
    // 可以在这里实现跳转到具体消息的功能
    console.log('点击了搜索结果消息:', message);
    // 暂时关闭搜索页面
    setShowSearchChat(false);
  };

  const handleBack = () => {
    navigate(-1);
  };

  // 处理背景选择弹窗
  const handleBackgroundClick = () => {
    setShowBackgroundModal(true);
  };

  // 关闭背景选择弹窗
  const closeBackgroundModal = () => {
    setShowBackgroundModal(false);
  };

  // 处理清空聊天记录点击
  const handleClearChatClick = () => {
    setShowClearChatModal(true);
  };

  // 关闭清空聊天记录弹窗
  const closeClearChatModal = () => {
    setShowClearChatModal(false);
  };

  // 确认清空聊天记录
  const confirmClearChat = async () => {
    if (selectedUser) {
      try {
        setIsClearingChat(true);
        // 调用API删除服务器上的聊天记录
        const response = await fetch(
          `http://localhost:3001/ysx/chat?from=${_currentUser.username}&to=${selectedUser.username}`,
          {
            method: 'DELETE',
          }
        );

        const result = await response.json();

        if (result.code === 200) {
          // 清空聊天记录成功
          setShowClearChatModal(false);
          // 返回聊天页面
          navigate(`/?chat=true&user=${selectedUser.username}`);
        } else {
          alert('清空聊天记录失败，请重试');
        }
      } catch (error) {
        console.error('清空聊天记录失败:', error);
        alert('清空聊天记录失败，请重试');
      } finally {
        setIsClearingChat(false);
      }
    }
  };

  // 选择预设背景
  const selectPresetBackground = (backgroundUrl: string) => {
    setSelectedBackground(backgroundUrl);
    if (selectedUser) {
      localStorage.setItem(
        `chatBackground_${selectedUser.username}`,
        backgroundUrl
      );
      setShowBackgroundModal(false);

      // 选择好背景图之后直接跳到与该用户的聊天页面
      navigate(`/?chat=true&user=${selectedUser.username}`);
    }
  };

  // 处理置顶聊天
  const handlePinChat = (isPinned: boolean) => {
    if (selectedUser) {
      // 更新本地状态
      setPinChat(isPinned);

      // 保存置顶状态到localStorage
      localStorage.setItem(
        `pinChat_${selectedUser.username}`,
        isPinned.toString()
      );

      // 触发聊天列表重新排序
      // 这里可以通过事件总线或者直接调用父组件的方法
      // 暂时使用localStorage来通知其他组件
      localStorage.setItem('chatListNeedsUpdate', 'true');
    }
  };

  // 选择本地图片
  const handleLocalImageSelect = (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const file = event.target.files?.[0];
    if (file && selectedUser) {
      const reader = new FileReader();
      reader.onload = e => {
        const imageUrl = e.target?.result as string;
        setSelectedBackground(imageUrl);
        localStorage.setItem(
          `chatBackground_${selectedUser.username}`,
          imageUrl
        );
        setShowBackgroundModal(false);

        // 选择好背景图之后直接跳到与该用户的聊天页面
        navigate(`/?chat=true&user=${selectedUser.username}`);
      };
      reader.readAsDataURL(file);
    }
  };

  // 如果显示搜索页面
  if (showSearchChat && selectedUser) {
    return (
      <SearchChat
        currentUser={_currentUser}
        selectedUser={selectedUser}
        onBack={handleSearchBack}
        onMessageClick={handleSearchMessageClick}
      />
    );
  }

  // 如果没有选中的用户，显示默认信息或重定向
  if (!selectedUser) {
    return (
      <div className="xq-container">
        <div className="xq-header">
          <button className="back-btn" onClick={handleBack}>
            ←
          </button>
          <div className="xq-title">聊天详情</div>
        </div>
        <div className="error-message">
          <p>未找到用户信息</p>
          <button onClick={handleBack} className="back-button">
            返回
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="xq-container">
      {/* 头部 */}
      <div className="xq-header">
        <button className="back-btn" onClick={handleBack}>
          ←
        </button>
        <div className="xq-title">聊天详情页面</div>
      </div>

      {/* 用户/群组信息 */}
      <div className="user-info-section">
        <div>
          <div className="profile-picture">
            <img src={selectedUser.image} alt={selectedUser.username} />
          </div>
          <div className="user-details">
            {/* <div className='user-name'>{selectedUser.username}</div> */}
          </div>
        </div>
        <div className="add-member-btn">
          <span>+</span>
        </div>
      </div>

      {/* 设置列表 */}
      <div className="settings-list">
        <div className="setting-item" onClick={handleSearchChatClick}>
          <span>查找聊天内容</span>
          <span className="arrow">›</span>
        </div>

        <div className="setting-item">
          <span>消息免打扰</span>
          <label className="toggle-switch">
            <input
              type="checkbox"
              checked={doNotDisturb}
              onChange={e => setDoNotDisturb(e.target.checked)}
            />
            <span className="slider" />
          </label>
        </div>

        <div className="setting-item">
          <span>置顶聊天</span>
          <label className="toggle-switch">
            <input
              type="checkbox"
              checked={pinChat}
              onChange={handlePinChatToggle}
            />
            <span className="slider" />
          </label>
        </div>

        <div className="setting-item">
          <span>提醒</span>
          <label className="toggle-switch">
            <input
              type="checkbox"
              checked={reminders}
              onChange={e => setReminders(e.target.checked)}
            />
            <span className="slider" />
          </label>
        </div>

        <div className="setting-item" onClick={handleBackgroundClick}>
          <span>设置当前聊天背景</span>
          <span className="arrow">›</span>
        </div>

        <div className="setting-item" onClick={handleClearChatClick}>
          <span>清空聊天记录</span>
        </div>

        <div className="setting-item">
          <span>投诉</span>
          <span className="arrow">›</span>
        </div>
      </div>

      {/* 背景选择弹窗 */}
      {showBackgroundModal && (
        <div
          className="background-modal-overlay"
          onClick={closeBackgroundModal}
        >
          <div className="background-modal" onClick={e => e.stopPropagation()}>
            <div className="modal-header">
              <h3>选择聊天背景</h3>
              <button className="close-btn" onClick={closeBackgroundModal}>
                ×
              </button>
            </div>

            <div className="background-options">
              {/* 预设背景图片 */}
              <div className="preset-backgrounds">
                <h4>预设背景</h4>
                <div className="background-grid">
                  {presetBackgrounds.map((bg, index) => (
                    <div
                      key={index}
                      className={`background-item ${selectedBackground === bg ? 'selected' : ''}`}
                      onClick={() => selectPresetBackground(bg)}
                    >
                      <img
                        src={bg}
                        alt={`背景${index + 1}`}
                        className="yuimg"
                      />
                    </div>
                  ))}
                </div>
              </div>

              {/* 本地图片选择 */}
              <div className="local-image-upload">
                <h4>选择本地图片</h4>
                <label className="upload-btn">
                  <input
                    type="file"
                    accept="image/*"
                    onChange={handleLocalImageSelect}
                    style={{ display: 'none' }}
                  />
                  <span>📁 选择图片</span>
                </label>
              </div>

              {/* 当前背景预览 */}
              {selectedBackground && (
                <div className="current-background">
                  <h4>当前背景</h4>
                  <div className="current-bg-preview">
                    <img src={selectedBackground} alt="当前背景" />
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* 清空聊天记录确认弹窗 */}
      {showClearChatModal && (
        <div className="background-modal-overlay" onClick={closeClearChatModal}>
          <div className="background-modal" onClick={e => e.stopPropagation()}>
            <div className="modal-header">
              <h3>清空聊天记录</h3>
              <button className="close-btn" onClick={closeClearChatModal}>
                ×
              </button>
            </div>
            <div className="clear-chat-content">
              <p>
                确定要清空与 <strong>{selectedUser?.username}</strong>{' '}
                的聊天记录吗？
              </p>
              <p style={{ fontSize: '14px', color: '#666', marginTop: '10px' }}>
                此操作不可撤销，所有聊天记录将被永久删除。
              </p>
              <div className="clear-chat-actions">
                <button className="cancel-btn" onClick={closeClearChatModal}>
                  取消
                </button>
                <button
                  className="confirm-btn"
                  onClick={confirmClearChat}
                  disabled={isClearingChat}
                >
                  {isClearingChat ? '清空中...' : '确认清空'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Xq;
